<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="图片地址" prop="imgSrc">
        <el-input
          v-model="queryParams.imgSrc"
          placeholder="请输入图片地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="顺序" prop="sequence">
        <el-input
          v-model="queryParams.sequence"
          placeholder="请输入顺序"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:shoreviwepager:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:shoreviwepager:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:shoreviwepager:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:shoreviwepager:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shoreviwepagerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="图片地址" align="center" prop="imgSrc" >
        <template slot-scope="scope">
          <el-image :src="scope.row.imgSrc" style="width: 380px;height: 214px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="顺序" align="center" prop="sequence" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:shoreviwepager:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:shoreviwepager:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改轮播图对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="图片地址" prop="imgSrc">
<!--          <el-input v-model="form.imgSrc" placeholder="请输入图片地址" />-->
          <!-- 图片上传 -->
          <el-upload
           :action="imgUpload.url"
           :on-success="handlePictureSuccess"
           :before-upload="beforePictureUpload"
           list-type="picture-card"
           :file-list="fileListShow"
           :on-preview="handlePictureCardPreview"
           :limit="limit"
           :multiple="multiplee"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <!-- 图片预览dialog -->
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%;" :src="dialogImageUrl">
          </el-dialog>
          <!-- 图片上传结束 -->

        </el-form-item>
        <el-form-item label="顺序" prop="sequence">
          <el-input v-model="form.sequence" placeholder="请输入顺序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listShoreviwepager, getShoreviwepager, delShoreviwepager, addShoreviwepager, updateShoreviwepager, exportShoreviwepager } from "@/api/system/shoreviwepager";
  import {getToken} from "@/utils/auth"

  export default {
    name: "Shoreviwepager",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 轮播图表格数据
        shoreviwepagerList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          imgSrc: null,
          sequence: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        },

        //图片上传判断是否有相同图片
        isCommonName: true,
        //修改时此属性用于接收数据库中图片存储list，图片才能正常显示
        fileListShow: [],
        //页面上存的暂时图片地址List
        fileListPut: [],
        dialogImageUrl: '',
        dialogVisible: false,
        imgUpload: {
          // 设置上传的请求头部
          // headers: {
          //   Authorization: "Bearer " + getToken()
          // },
          // 图片上传的方法地址:
          // url: process.env.VUE_APP_BASE_API + "/api/shoreviwepager/multiPicturesUpload",
          url: process.env.VUE_APP_BASE_API + "/common/upload",
          url2: process.env.VUE_APP_BASE_API
        },
        multiplee: false,
        limit: 1
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询轮播图列表 */
      getList() {
        this.loading = true;
        listShoreviwepager(this.queryParams).then(response => {
          this.shoreviwepagerList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.fileListShow=[],
          //页面上存的暂时图片地址List
        this.fileListPut = [],
        this.dialogImageUrl='',
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          imgSrc: null,
          sequence: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加轮播图";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getShoreviwepager(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改轮播图";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateShoreviwepager(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addShoreviwepager(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除轮播图编号为"' + ids + '"的数据项？').then(function() {
          return delShoreviwepager(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$modal.confirm('是否确认导出所有轮播图数据项？').then(() => {
          this.exportLoading = true;
          return exportShoreviwepager(queryParams);
        }).then(response => {
          this.$download.name(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
      },


      //图片上传前的相关判断
      beforePictureUpload(file){
        //每次进来初始化 isCommonName 为true
        this.isCommonName = true;
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        //判断是否有相同的图片，如何有即提示并添加失败
        if(this.fileListPut.length > 0){
          this.fileListPut.forEach((item,index)=>{
            if(item.name == file.name){
              this.$message.error('已存在相同的图片！');
              this.isCommonName = false;
            }
          })
        }
        if (!isJPG) {
          this.$message.error('请上传图片格式的文件！');
        }
        if (!isLt2M) {
          this.$message.error('上传的图片不能超过2MB!');
        }
        return isJPG && isLt2M && this.isCommonName;
      },
      //图片上传删除
      handleRemove(file, fileList) {
        //根据传进来删除的file里图片，同时删除保存在fileListPut的相同图片
        if(this.fileListPut.length > 0){
          this.fileListPut = this.fileListPut.filter((item, index)=>{
            return item.name != file.name;
          })
        }
      },
      //图片预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      //图片上传成功后的回调
      handlePictureSuccess(res, file){
        //设置图片访问路径
        alert(res.url);

        const imgObjectUrl = this.imgUpload.url2 +"/"+ file.response.fileName;
        alert(imgObjectUrl)
        this.form.imgSrc = imgObjectUrl;
        //这是每个成功上传图片，以对象的形式保存在一个数组中，进而以JSON格式保存在数据库中某个字段里
        // let currentFile = {name: '',url: ''};
        // currentFile.name = file.name;
        // currentFile.url = imgObjectUrl;
        // //往此数组中保存当前图片对象
        // this.fileListPut.push(currentFile);
        this.reset();
      },
    }
  };
</script>
